package com.sylar.happyreader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.Callable;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sylar.happyreader.adapter.BookPageAdapter;
import com.sylar.happyreader.adapter.BookStyleAdapter;
import com.sylar.happyreader.listener.Callback;
import com.sylar.happyreader.net.HttpTool;
import com.sylar.happyreader.tools.Config;
import com.sylar.happyreader.tools.TaskUtils;
import com.sylar.happyreader.tools.Utils;
import com.sylar.happyreader.view.MyHorizontalScrollView;
import com.sylar.happyreader.view.MyHorizontalScrollView.SizeCallbackForMenu;
import com.sylar.happyreader.view.ShelvesView;
import com.sylar.happyreader.view.VerticalTextView;

public class BookListActivity extends Activity implements Callable<String>, Callback<String>, OnClickListener, OnItemClickListener {

	public static String[] manLists;
	public static String[] woManLists;

	public static ArrayList<String> mBookArrayList;
	public LinearLayout classLayout;
	public RelativeLayout bookLayout;
	private LinearLayout localbookLayout;
	private ShelvesView mGrid;
	private String searchBookName;
	private MyHorizontalScrollView scrollView;
	private VerticalTextView vtv_man;
	private VerticalTextView vtv_woman;
	private VerticalTextView vtv_local;
	private VerticalTextView vtv_about;
	private VerticalTextView vtv_marklets;

	private static int TASK_TYPE;
	private static final int CHANGE_BOOKLISTS = 1;
	private static final int GET_BOOKPAGELISTS = CHANGE_BOOKLISTS + 1;
	private static final int SEARCH_BOOK = GET_BOOKPAGELISTS + 1;
	private static final int TASK_GET_MAN_LIST = SEARCH_BOOK + 1;
	private static final int TASK_GET_WOMAN_LIST = TASK_GET_MAN_LIST + 1;
	private static final int TASK_GET_BOOK_CONTENT = TASK_GET_WOMAN_LIST + 1;

	private BookPageAdapter bookPageAdapter;
	private BookStyleAdapter bookClassAdapter;
	private ListView mBookClassList;

	public static String style = "";
	private String sex = "man";
	private String bookName;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		LayoutInflater inflater = LayoutInflater.from(this);

		scrollView = (MyHorizontalScrollView) inflater.inflate(R.layout.main_parent, null);

		setContentView(scrollView);

		int scrollToViewIdx = 1;

		View menuLayout = inflater.inflate(R.layout.left_menu, null);
		View bookGridLayout = inflater.inflate(R.layout.main, null);

		View[] children = new View[] { menuLayout, bookGridLayout };
		scrollView.initViews(children, scrollToViewIdx, new SizeCallbackForMenu(menuLayout));

		ImageView btn_menu = (ImageView) findViewById(R.id.btn_t_menu);
		scrollView.setShowMenuBtn(btn_menu);

		ImageView btn_t_search = (ImageView) findViewById(R.id.btn_t_search);
		btn_t_search.setOnClickListener(this);

		mGrid = (ShelvesView) findViewById(R.id.grid_shelves);
		mGrid.setFastScrollEnabled(true);
		mGrid.setOnItemClickListener(this);

		localbookLayout = (LinearLayout) findViewById(R.id.localbookLayout);


		classLayout = (LinearLayout) findViewById(R.id.classLayout);
		bookLayout = (RelativeLayout) findViewById(R.id.bookLayout);
		mBookClassList = (ListView) findViewById(R.id.bookclass_item_list);

		LayoutInflater mInflater = LayoutInflater.from(this);
		View mViewheader = mInflater.inflate(R.layout.head, null);
		TextView headText = (TextView) mViewheader.findViewById(R.id.headText);
		headText.setText("分类选择");
		mBookClassList.addHeaderView(mViewheader, null, false);
		mBookClassList.setOnItemClickListener(this);
		mBookClassList.setFastScrollEnabled(true);

		vtv_man = (VerticalTextView) findViewById(R.id.vtv_man);
		vtv_woman = (VerticalTextView) findViewById(R.id.vtv_woman);
		vtv_local = (VerticalTextView) findViewById(R.id.vtv_local);
		vtv_about = (VerticalTextView) findViewById(R.id.vtv_about);
		vtv_marklets = (VerticalTextView) findViewById(R.id.vtv_marklets);
		vtv_marklets.setOnClickListener(this);
		vtv_man.setOnClickListener(this);
		vtv_woman.setOnClickListener(this);
		vtv_local.setOnClickListener(this);
		vtv_about.setOnClickListener(this);

		style = this.getIntent().getStringExtra("style");

		if (mBookArrayList != null && mBookArrayList.size() > 1) {
//			mGrid.setAdapter(new BooksAdapter(this, mBookArrayList));
		}

	}
	
	

	@Override
	protected void onPause() {
		super.onPause();
		// MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// MobclickAgent.onResume(this);
	}

//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//		if (classLayout != null && classLayout.getVisibility() == View.VISIBLE) {
//			classLayout.setVisibility(View.GONE);
//			bookLayout.setVisibility(View.VISIBLE);
//			scrollView.smoothScrollTo(0, 0);
//		} else {
//			if (scrollView.canCloseMenu()) {
//
//			} else {
//				if (keyCode == KeyEvent.KEYCODE_BACK) {
//					new AlertDialog.Builder(BookListActivity.this).setTitle("小说书城提示").setMessage("确定退出使用吗?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
//						public void onClick(DialogInterface dialog, int whichButton) {
//							android.os.Process.killProcess(android.os.Process.myPid());
//							System.exit(1);
//						}
//					}).setNegativeButton("再看一会儿", new DialogInterface.OnClickListener() {
//						public void onClick(DialogInterface dialog, int which) {
//						}
//					}).show();
//				}
//				return false;
//			}
//		}
//		return true;
//	}


	public String call() throws Exception {
		String result = "";
		String url = "";
		String httpResult = "";
		switch (TASK_TYPE) {
		case CHANGE_BOOKLISTS:
			url = Config.RequestUri + "sex=" + sex + "&style=" + Uri.encode(style);
			httpResult = HttpTool.getString(getApplicationContext(), url);
			result = httpResult;
			break;

		case GET_BOOKPAGELISTS:
			url = Config.RequestUri + "sex=" + sex + "&style=" + Uri.encode(style) + "&bookName=" + Uri.encode(bookName);
			httpResult = HttpTool.getString(getApplicationContext(), url);
			if (httpResult != null && !"".equals(httpResult)) {
				Config.pagelists = Utils.SubArray(httpResult.split(".txt"));
				result = "ok";
			} else {
				result = "error";
			}
			break;

		case SEARCH_BOOK:
			url = Config.RequestUri + "searchBook=" + Uri.encode(searchBookName);
			String response = HttpTool.getString(getApplicationContext(), url);
			if ("还未收录此书".equals(response.trim())) {
				result = "nobook";
			} else if (response != null && !"".equals(response.trim())) {
				String[] params = response.split("/");
				sex = params[0].trim();
				style = params[1].trim();
				bookName = params[2].trim();
				mBookArrayList = new ArrayList<String>();
				mBookArrayList.add(bookName);
				result = "ok";
			}
			break;
		case TASK_GET_MAN_LIST:
			String manlists = HttpTool.getString(getApplicationContext(), Config.RequestUri + "sex=man");
			result = manlists;
			break;
		case TASK_GET_WOMAN_LIST:
			String woManlists = HttpTool.getString(getApplicationContext(), Config.RequestUri + "sex=woman");
			result = woManlists;
			break;

		case TASK_GET_BOOK_CONTENT:
			url = Config.RequestUri + "sex=" + sex + "&style=" + Uri.encode(style) + "&bookName=" + Uri.encode(bookName) + "&pageCount=" + Uri.encode(Config.nowPage);
			String msg = HttpTool.getString(getApplicationContext(), url);
			if (msg != null) {
				msg = msg.replace("光影之间团队分享", "");
				msg = msg.replace("更多精彩内容请访问", "");
				msg = msg.replace("http://www.newperl.com", "");
				ReadBookActivity.msg = msg;
			}
			result = msg;
			break;
		}
		return result;
	}

	public void onCallback(String pCallbackValue) {

		switch (TASK_TYPE) {
		case CHANGE_BOOKLISTS:
			if (pCallbackValue != null && !"".equals(pCallbackValue)) {
				String[] bookname = pCallbackValue.split(":");
				bookname = Utils.SubArray(bookname);
				mBookArrayList = new ArrayList<String>(Arrays.asList(bookname));
//				mGrid.setAdapter(new BooksAdapter(this, mBookArrayList));
				classLayout.setVisibility(View.GONE);
				localbookLayout.setVisibility(View.GONE);
				bookLayout.setVisibility(View.VISIBLE);
				scrollView.smoothScrollTo(0, 0);
			} else {
				Toast.makeText(this, "加载失败了哦", Toast.LENGTH_SHORT).show();
			}

			break;
		case GET_BOOKPAGELISTS:
			if ("ok".equals(pCallbackValue)) {
				if (Config.pagelists != null && Config.pagelists.length > 0) {
					bookPageAdapter = new BookPageAdapter(getApplicationContext(), Config.pagelists, bookName);
					mBookClassList.setAdapter(bookPageAdapter);
					mBookClassList.setTag(GET_BOOKPAGELISTS);
					bookLayout.setVisibility(View.GONE);
					localbookLayout.setVisibility(View.GONE);
					classLayout.setVisibility(View.VISIBLE);
					scrollView.smoothScrollTo(0, 0);
				} else {
					Toast.makeText(this, "加载失败了哦", Toast.LENGTH_SHORT).show();
				}

			} else {
				Toast.makeText(this, "加载失败了哦", Toast.LENGTH_SHORT).show();
			}
			break;

		case SEARCH_BOOK:
//			if ("ok".equals(pCallbackValue))
//				mGrid.setAdapter(new BooksAdapter(this, mBookArrayList));
//			else if ("nobook".equals(pCallbackValue))
//				Toast.makeText(this, "还未收录此本书籍哦", Toast.LENGTH_SHORT).show();
//			else
//				Toast.makeText(this, "加载失败了哦", Toast.LENGTH_SHORT).show();
			break;

		case TASK_GET_MAN_LIST:
			if (!TextUtils.isEmpty(pCallbackValue)) {
				try {
					String[] manList = pCallbackValue.split(":");
					manList = Utils.SubArray(manList);
					bookClassAdapter = new BookStyleAdapter(this, 0, manList);
					mBookClassList.setAdapter(bookClassAdapter);
					mBookClassList.setTag(CHANGE_BOOKLISTS);
					bookLayout.setVisibility(View.GONE);
					classLayout.setVisibility(View.VISIBLE);
					localbookLayout.setVisibility(View.GONE);
					scrollView.smoothScrollTo(0, 0);
					sex = "man";
				} catch (Exception e) {
					Toast.makeText(this, "加载失败了哦", Toast.LENGTH_SHORT).show();
				}

			} else {
				Toast.makeText(this, "加载失败了哦", Toast.LENGTH_SHORT).show();
			}
			break;
		case TASK_GET_WOMAN_LIST:
			if (!TextUtils.isEmpty(pCallbackValue)) {
				String[] manList = pCallbackValue.split(":");
				manList = Utils.SubArray(manList);
				bookClassAdapter = new BookStyleAdapter(this, 0, manList);
				mBookClassList.setAdapter(bookClassAdapter);
				mBookClassList.setTag(CHANGE_BOOKLISTS);
				bookLayout.setVisibility(View.GONE);
				classLayout.setVisibility(View.VISIBLE);
				localbookLayout.setVisibility(View.GONE);
				scrollView.smoothScrollTo(0, 0);
				sex = "woman";
			} else {
				Toast.makeText(this, "加载失败了哦", Toast.LENGTH_SHORT).show();
			}
			break;
		case TASK_GET_BOOK_CONTENT:
			if (!TextUtils.isEmpty(pCallbackValue)) {
				Intent intent = new Intent(this, ReadFilpBookActivity.class);
				intent.putExtra("style", style);
				intent.putExtra("sex", sex);
				intent.putExtra("bookName", bookName);
				this.startActivity(intent);
			} else {
				Toast.makeText(this, "加载失败了哦", Toast.LENGTH_SHORT).show();
			}
			break;
		}

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_t_search:
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.dialogview, null);
			final EditText bookNameText = (EditText) textEntryView.findViewById(R.id.bookname_edit);
			new AlertDialog.Builder(this).setTitle("请输入书名").setView(textEntryView).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					String bookName = bookNameText.getText().toString().trim();

					if (bookName != null && !"".equals(bookName)) {
						searchBookName = bookName;
						TASK_TYPE = SEARCH_BOOK;
						TaskUtils.doAsync(BookListActivity.this, null, "正在加载中哦..", BookListActivity.this, BookListActivity.this);
					}

				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				}
			}).show();
			break;

		case R.id.vtv_man:
			do_getManList();
			break;
		case R.id.vtv_woman:
			do_getWoManList();
			break;
		case R.id.vtv_local:
			do_getLocalBook();
			break;
		case R.id.vtv_about:
			do_aboutUs();
			break;

		case R.id.vtv_marklets:
			to_myMarklets();
			break;
		
		}
	}
	
	
	
	void to_myMarklets() {

	}

	void do_getManList() {
		TASK_TYPE = TASK_GET_MAN_LIST;
		vtv_man.setBackgroundResource(R.drawable.menu_bg);
		vtv_about.setBackgroundDrawable(null);
		vtv_local.setBackgroundDrawable(null);
		vtv_woman.setBackgroundDrawable(null);
		TaskUtils.doAsync(this, null, null, this, this);
	}

	void do_getWoManList() {
		TASK_TYPE = TASK_GET_WOMAN_LIST;
		vtv_man.setBackgroundDrawable(null);
		vtv_woman.setBackgroundResource(R.drawable.menu_bg);
		vtv_about.setBackgroundDrawable(null);
		vtv_local.setBackgroundDrawable(null);
		TaskUtils.doAsync(this, null, null, this, this);
	}

	void do_getLocalBook() {
		vtv_man.setBackgroundDrawable(null);
		vtv_woman.setBackgroundDrawable(null);
		vtv_about.setBackgroundDrawable(null);
		vtv_local.setBackgroundResource(R.drawable.menu_bg);
		bookLayout.setVisibility(View.GONE);
		classLayout.setVisibility(View.GONE);
		localbookLayout.setVisibility(View.VISIBLE);
	}

	void do_aboutUs() {
		vtv_man.setBackgroundDrawable(null);
		vtv_woman.setBackgroundDrawable(null);
		vtv_about.setBackgroundResource(R.drawable.menu_bg);
		vtv_local.setBackgroundDrawable(null);
	}

	void do_getClassBook(String bclass) {
		if (TextUtils.isEmpty(bclass))
			return;
		style = bclass;
		TASK_TYPE = CHANGE_BOOKLISTS;
		TaskUtils.doAsync(this, null, null, this, this);
	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (parent != null && parent == mBookClassList) {
			Adapter adapter = mBookClassList.getAdapter();
			try {
				int tag = (Integer) parent.getTag();
				if (adapter != null && tag == CHANGE_BOOKLISTS) {
					String style = bookClassAdapter.getItem(position - 1);
					do_getClassBook(style);
				} else if (adapter != null && tag == GET_BOOKPAGELISTS) {
					// TODO
					TASK_TYPE = TASK_GET_BOOK_CONTENT;
					Config.pageNo = position - 1;
					Config.nowPage = Config.pagelists[Config.pageNo];
					TaskUtils.doAsync(BookListActivity.this, null, "数据加载中哦..", BookListActivity.this, BookListActivity.this);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

		} else if (parent != null && parent == mGrid) {
			bookName = mBookArrayList.get(position);
			TASK_TYPE = GET_BOOKPAGELISTS;
			TaskUtils.doAsync(BookListActivity.this, null, "正在加载中哦..", BookListActivity.this, BookListActivity.this);
		}
	}

	// 拦截MENU按钮
	public boolean onMenuOpened(int featureId, Menu menu) {
		scrollView.showOrCloseMenu();
		return false;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");
		return super.onCreateOptionsMenu(menu);
	}
}